package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/4/21 11:10
 */
public class MyDimUtil {
    public static JSONObject readDim(Connection conn, String table, Object id) {
        // 先去redis, redis没有再去hbase
        Jedis client = MyRedisUtil.getClient();
        String key = table + ":" + id;
        String dim = client.get(key);
        
        JSONObject obj = new JSONObject();
        if (dim != null) {
            //            System.out.println(table + "的id:" + id + " 走缓存!");
            client.close();
            obj = JSON.parseObject(dim);
        } else {
            //            System.out.println(table + "的id:" + id + " 走数据库!");
            String sql = "select * from " + table + " where id=?";
            Object[] args = {id};
            
            List<JSONObject> list = MyJdbcUtil
                .queryList(conn,
                           sql,
                           args,
                           JSONObject.class,
                           false);
            
            if (list != null && !list.isEmpty()) {
                obj = list.get(0);
                // 从hbase读取到了维度数据, 把这个维度数据存储到redis中
                client.setex(key, 24 * 60 * 60, obj.toJSONString());
            }
            
        }
        client.close();
        return obj;
    }
    
    public static JSONObject readDim(Connection conn, Jedis client, String table, Object id) {
        // 先去redis, redis没有再去hbase
        String key = table + ":" + id;
        String dim = client.get(key);
        
        JSONObject obj = new JSONObject();
        if (dim != null) {
            //            System.out.println(table + "的id:" + id + " 走缓存!");
            obj = JSON.parseObject(dim);
        } else {
            //            System.out.println(table + "的id:" + id + " 走数据库!");
            String sql = "select * from " + table + " where id=?";
            Object[] args = {id};
            
            List<JSONObject> list = MyJdbcUtil
                .queryList(conn,
                           sql,
                           args,
                           JSONObject.class,
                           false);
            
            if (list != null && !list.isEmpty()) {
                obj = list.get(0);
                // 从hbase读取到了维度数据, 把这个维度数据存储到redis中
                client.setex(key, 24 * 60 * 60, obj.toJSONString());
            }
            
        }
        return obj;
    }
}
